package edu.bw.controller;

import edu.bw.common.CommonResult;
import edu.bw.dto.InsertUserForm;
import edu.bw.dto.SelectUserByConditionForm;
import edu.bw.dto.UpdateUserForm;
import edu.bw.po.User;
import edu.bw.service.UserService;
import edu.bw.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public CommonResult login(@RequestBody User user) {
        // 调用UserService处理登录业务逻辑
        Integer userId = userService.userLogin(user);

        // 构建并返回结果
        return CommonResult.ok().put("result", (userId != null) ? "登录成功" : "登录失败");
    }
    /**
     * 根据条件查询用户
     */
    @PostMapping("/selectUserByCondition")
    public CommonResult selectUserByCondition(@RequestBody SelectUserByConditionForm selectCondition) {
        PageUtils pageUtils = userService.selectUserByCondition(selectCondition);
        return CommonResult.ok().put("page", pageUtils);
    }

    /**
     * 插入新用户
     */
    @PostMapping("/insert")
    public CommonResult insert(@RequestBody InsertUserForm insertUserForm) {
        Integer rows = userService.insert(insertUserForm);
        return CommonResult.ok().put("rows", rows);
    }

    @PostMapping("/selectById")
    public CommonResult selectById(@RequestBody Map<String, Integer> params) {
        List<Map<String, Object>> list = userService.selectById(params.get("userId"));
        return CommonResult.ok(list.get(0));
    }

    @PostMapping("/update")
    public CommonResult updateUser(@RequestBody UpdateUserForm updateUserForm) {
        Integer rows = userService.update(updateUserForm);
        return CommonResult.ok().put("rows", rows);
    }
    /**
     * 批量删除用户
     */
    @PostMapping("/deleteUserByIds")
    public CommonResult deleteUserByIds(@RequestBody Map<String, List<Integer>> params) {
        List<Integer> ids = params.get("ids");
        Integer rows = userService.deleteUserByIds(ids);
        return CommonResult.ok().put("rows", rows);
    }
}
